package io.github.jyrmc.deploy.task

import cn.hutool.core.util.CharsetUtil
import cn.hutool.extra.ssh.JschUtil
import io.github.jyrmc.deploy.utils.SFTPUploader
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.Optional
import org.gradle.api.tasks.TaskAction


/**
 * ssh支持的task
 *
 * @author jyRMc
 * @since 2024/9/14 16:44
 **/
open class DeployJavaApplicationTask : DefaultTask() {
    @Input
    @Optional
    lateinit var host: String

    @Input
    var port: Int = 22

    @Input
    var username: String = "root"

    @Input
    @Optional
    lateinit var password: String

    @Input
    @Optional
    lateinit var localJarPath: String

    @Input
    @Optional
    lateinit var args: MutableList<String>

    @Input
    @Optional
    lateinit var deployPath: String

    @Input
    @Optional
    lateinit var javaHome: String


    @TaskAction
    fun sshAction() {
        // access java jar name
        val jarName = if (localJarPath.endsWith(".jar")) {
            localJarPath.substring(localJarPath.lastIndexOf("/") + 1)
        } else {
            localJarPath.substring(localJarPath.lastIndexOf("/") + 1) + ".jar"
        }
        if (javaHome.isBlank()) {
            javaHome = ""
        }
        if (javaHome.endsWith("/")) {
            javaHome = javaHome.substring(0, javaHome.length - 1)
        }

        // upload jar to remote server
        val onlyJarName = jarName.substring(0, jarName.lastIndexOf("-"))
        if (args.isEmpty()) {
            args.add("java.security.egd=file:/dev/./urandom")
        }
        var argsStr = ""
        for (arg in args) {
            argsStr += "-D${arg} "
        }
        val session = JschUtil.getSession(host, port, username, password)

        JschUtil.exec(session, "mkdir -p $deployPath", CharsetUtil.CHARSET_UTF_8)
        SFTPUploader.uploadFile(session, localJarPath, deployPath)

        JschUtil.exec(
            session,
            "ps -ef | grep $onlyJarName | grep -v grep | awk '{print ${'$'}2}' | xargs kill -9",
            CharsetUtil.CHARSET_UTF_8
        )

        // nohup java -jar $jarName $argsStr > /dev/null 2>&1 &
        JschUtil.exec(session, "source /etc/profile", CharsetUtil.CHARSET_UTF_8)
        println("================================= Current Java Version  =================================")
        JschUtil.exec(session, "${javaHome}/bin/java -version", CharsetUtil.CHARSET_UTF_8)
        println("================================= Deploy Java Application =================================")
        val runJavaAppCommandLine =
            "nohup ${javaHome}/bin/java -jar $argsStr ${deployPath}/${jarName} > ${deployPath}/nohup.log 2>&1 &"
        JschUtil.exec(session, runJavaAppCommandLine, CharsetUtil.CHARSET_UTF_8)
        JschUtil.close(session)
        println("================================= 🚩🚩🚩Finish deploy  =================================")
    }
}